package com.LeeCode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树的层序遍历
 */

public class Code102 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(0, new TreeNode(1), new TreeNode(2, null, new TreeNode(3)));

        System.out.println(new Code102().levelOrder(root));
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> tmp = new ArrayList<>();
        queue.add(root);
        queue.add(null); // 添加第一层结束标记
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            if (node != null) {
                tmp.add(node.val);
                // 将子节点加入队列
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            } else { // 遇到结束标记
                res.add(tmp);
                queue.add(null); //添加下一层的结束标记
                if (queue.size() == 1 && queue.peek() == null) {
                    break; // 最后一个结束标记
                }
                tmp = new ArrayList<>();
            }
        }
        return res;
    }

    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ans.add(level);
        }

        return ans;
    }
}
